package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
	"webx/models/dao"

	"webx/config"
	"webx/routers"
	"webx/utils"
)

// @title Gin Web App API
// @version 1.0
// @description This is a sample gin web application
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.email support@example.com
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api
func main() {
	// 加载配置
	config.Load()

	// 初始化日志
	utils.InitLogger()
	defer utils.SyncLogger()

	// 初始化验证器
	utils.InitValidator()

	// 设置路由
	router := routers.SetupRouter()

	// 启动服务器
	cfg := config.GetConfig().App
	srv := &http.Server{
		Addr:    fmt.Sprintf(":%d", cfg.Port),
		Handler: router,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	log.Printf("Server started on port %d in %s mode\n", cfg.Port, cfg.Env)

	// 等待中断信号以优雅地关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutting down server...")

	// 设置 5 秒的超时时间
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}

	// 关闭数据库连接
	if err := dao.CloseDB(); err != nil {
		log.Println("Failed to close database connection:", err)
	}

	if err := dao.CloseRedis(); err != nil {
		log.Println("Failed to close redis connection:", err)
	}

	log.Println("Server exiting")
}
